<template>

  <el-card class="box-card">
    <h2>登录含光AI应用开发平台</h2>
    <el-form :model="form" @submit.prevent="login">
      <el-form-item label="账号">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input type="password" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit"  style="width: 100%;">登录</el-button>
      </el-form-item>
    </el-form>
    <p>没有账号？<router-link to="/register">去注册</router-link></p>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    };
  },
  methods: {
    async login() {
      try {
        const response = await fetch(`${import.meta.env.VITE_API_URL}/user/login`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(this.form)
        });
        const data = await response.json();
        if (response.ok) {
          localStorage.setItem('access_token', data.data.access_token); // Store token in local storage
          this.$router.push('/'); // Redirect to home page after login
        } else {
          ElMessage.error(data.msg);
        }
      } catch (error) {
        console.error(error);
      }
    }
  },
  mounted() {
    const token = localStorage.getItem('access_token');
    if (token) {
      this.$router.push('/');
    }
  }
};
</script>

<style>
.box-card {
  width: 400px;
  margin: 100px auto;
}


</style>